package com.geek.factory.service.strategy;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.geek.factory.config.AliyunOSSCConfig;
import com.geek.factory.config.AliyunOSSCConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/6/24
 */
@Component("aliyun")
public class AliyunUploadStrategy implements UploadStrategy{

    private final AliyunOSSCConfig aliyunOSSCConfig;
    private OSS ossClient;

    @Autowired
    public AliyunUploadStrategy(AliyunOSSCConfig aliyunOSSCConfig){
        this.aliyunOSSCConfig = aliyunOSSCConfig;
    }

    //初始化
    @PostConstruct
    public void init(){
        //创建OSSClient实例
        ossClient = new OSSClientBuilder().build(aliyunOSSCConfig.getEndpoint(), aliyunOSSCConfig.getAccessKey(), aliyunOSSCConfig.getSecretKey());
    }

    //销毁
    @PreDestroy
    public void destroy(){
        //关闭OSSClient
        ossClient.shutdown();
    }

    @Override
    public String uploadFile(MultipartFile file) {
        if(file!=null){
            String oldName = file.getOriginalFilename();
            if(StringUtils.hasLength(oldName) && oldName.lastIndexOf(".")>0){
                //asda7878adsa898689sfasf1.png
                String newName = UUID.randomUUID()+oldName;
                //日期文件夹    2025/06/24
                String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
                //存储的文件名   2025/06/24/asda7878adsa898689sfasf1.png
                String fileName = date+"/"+newName;
                try {
                    //TODO 调用方法实现上传
                    ossClient.putObject(aliyunOSSCConfig.getBucket(), fileName, file.getInputStream());

                    //TODO 返回阿里云OSS服务器上的存储外链地址
                    //格式例如：https://yygh-igeek-user.oss-cn-shanghai.aliyuncs.com/2021/05/06/0a4954938c5e488886924a01eca95ebd1.png
                    String url = "https://"+aliyunOSSCConfig.getBucket()+"."+aliyunOSSCConfig.getEndpoint()+"/"+fileName;
                    return url;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    @Override
    public boolean deleteFile(String url) {
        String fileName = url.replaceAll("https://"+aliyunOSSCConfig.getBucket()+"."+aliyunOSSCConfig.getEndpoint()+"/" , "");
        //删除文件
        try{
            ossClient.deleteObject(aliyunOSSCConfig.getBucket(), fileName);
            return true;
        }catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
